package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;


    // 用户下单
    @Override
    public void submit(Order order) {
        // 1.获取登录人user对象
        User user = UserHolder.get();
        if (user == null) {
            throw new CustomException("登录人为空不能下单");
        }
        // 2.根据id查询收货地址
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空不能下单");
        }
        // 3.获取购物车列表
        List<Cart> cartList = cartService.list();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空不能下单");
        }

        // 通过mp生成订单id
        long orderId = IdWorker.getId();

        // 订单金额
        BigDecimal amount = new BigDecimal(0);

        // 4.遍历购物车
        for (Cart cart : cartList) {
            // 封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName()); // 菜品或套餐名称
            orderDetail.setOrderId(orderId); // 订单id
            orderDetail.setDishId(cart.getDishId()); // 菜品id
            orderDetail.setSetmealId(cart.getSetmealId());// 套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());// 口味
            orderDetail.setNumber(cart.getNumber()); // 数量
            orderDetail.setAmount(cart.getAmount()); // 金额
            orderDetail.setImage(cart.getImage()); // 图片
            // mapper保存
            orderDetailMapper.insert(orderDetail);

            // 累加
            // amount=amount+(cart.getAmount()*cart.getNumber());
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        // 5.保存订单
        // 5-1 封装
        order.setId(orderId); // 订单id
        order.setNumber(String.valueOf(orderId)); // 订单号
        order.setStatus(1); // 待付款
        order.setUserId(user.getId()); // 下单用户id
        order.setOrderTime(new Date()); // 下单时间
        order.setCheckoutTime(new Date()); // 结账时间
        order.setAmount(amount); // 实收金额
        order.setUserName(user.getName()); // 下单用户名称
        order.setPhone(address.getPhone()); // 收货人手机号
        order.setAddress(address.getDetail()); // 收货人地址
        order.setConsignee(address.getConsignee()); // 收货人姓名
        // 5-2 mapper保存
        orderMapper.insert(order);

        // 6.清空购物车
        cartService.clean();
    }


    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {

        //1. 设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2. 设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());

        //3. 设置排序(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4. 执行查询,得到订单信息
        page = orderMapper.selectPage(page, wrapper);

        //5. 遍历订单列表,得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6. 根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }
        //7. 返回
        return page;
    }

    //订单明细
    @Override
    public Page<Order> findByPage2(Long number, Date beginTime, Date endTime, Integer pageNum, Integer pageSize) {
        //1. 设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2. 设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null, Order::getId, number);
        wrapper.ge(beginTime != null, Order::getOrderTime, beginTime);
        wrapper.le(endTime != null, Order::getOrderTime, endTime);

        //3. 设置排序(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4. 执行查询,得到订单信息
        page = orderMapper.selectPage(page, wrapper);

        //5. 遍历订单列表,得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6. 根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }
        //7. 返回
        return page;
    }

}
